﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class Episodes : System.Web.UI.Page
{
    ManageDatabase data;
    List<Episode> episodes;
    Season season;
    Serie series;
    List<Comment> comments;
    Comment newComment;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (data == null)
        {
            data = new ManageDatabase();
        }
        if (!IsPostBack)
        {
            if (Request.QueryString["evad"] != null)
            {
                String s = Request.QueryString["evad"].ToString();
                Initialize(Convert.ToInt32(s));
            }
            else
            {
                Response.Redirect("Series.aspx");
            }
        }
    }

    private void Initialize(int seasonId)
    {
        try
        {
            season = data.GetWholeSeason(seasonId, true);
            series = data.GetWholeSerie(season.seriesId, true);

            if (!User.IsInRole("admin") && Functions.GetUserId() != season.userID && season.status != 1)
            {
                Response.Redirect("~/Default.aspx");
            }

            //SeasonPanel.CssClass = "panel";
            SeasonInfo.CssClass = "infoTalbe";
            SeasonHunTitle.CssClass = "titleHun";
            SeasonOrigTitle.CssClass = "titleOrig";
            SeasonStatus.CssClass = "status";
            SeasonReleaseDate.CssClass = "releaseDate";
            SeasonDescription.CssClass = "description";
            SeasonDirectors.CssClass = "directors";
            SeasonWriters.CssClass = "writers";
            SeasonStars.CssClass = "stars";
            SeasonGenres.CssClass = "genres";
            SeasonSeries.CssClass = "series";

            if (season.status != 1)
            {
                SeasonStatus.Text = "   (Nem engedélyezett)";
            } 

            if (season.imgUrl != "")
                SeasonImg.ImageUrl = "~/Pic/" + season.imgUrl;
            else
                SeasonImg.ImageUrl = "~/images/nopic.png";
            SeasonImg.Width = 300;
            SeasonImg.Height = 300;
            SeasonHunTitle.Text = season.season.ToString() + ". Évad";
            SeasonOrigTitle.Text = "Season " + season.season.ToString();
            SeasonSeries.Text = series.titleHun;
            SeasonSeries.NavigateUrl = "Seasons.aspx?sorozat=" + season.seriesId.ToString();
            SeasonDirectors.Text = series.directors;
            SeasonWriters.Text = series.writers;
            SeasonStars.Text = series.stars;
            SeasonReleaseDate.Text = String.Format("{0:yyyy.MM.dd}", season.releaseDate);
            SeasonDescription.Text = season.description;

            foreach (ListItem genre in series.genres)
            {
                SeasonGenres.Text += genre.Text + ", ";
            }
            if (SeasonGenres.Text.Length > 0)
                SeasonGenres.Text = SeasonGenres.Text.Substring(0, SeasonGenres.Text.Length - 2);

            if (User.IsInRole("admin"))
            {
                toolDiv.Visible = true;
                EditButton.Visible = true;
                DeleteButton.Visible = true;
                if (season.status == 1)
                {
                    StatusMinusButton.Visible = true;
                    StatusPlusButton.Visible = false;
                }
                else
                {
                    StatusMinusButton.Visible = false;
                    StatusPlusButton.Visible = true;
                }
            }
            else if (User.IsInRole("user") && Functions.GetUserId().Equals(season.userID))
            {
                toolDiv.Visible = true;
                EditButton.Visible = true;
                DeleteButton.Visible = false;
            }
            else
            {
                toolDiv.Visible = false;
                EditButton.Visible = false;
                DeleteButton.Visible = false;
            }

            episodes = data.GetEpisodesPreview(seasonId);

            foreach (Episode item in episodes)
            {
                if (item.status == 1 || User.IsInRole("admin") || Functions.GetUserId() == item.userID)
                {
                    Panel EpisodePanel = new Panel();
                    HtmlGenericControl FieldSet = new HtmlGenericControl("fieldset");
                    Table EpisodeTable = new Table();
                    TableRow EpisodeRow = new TableRow();
                    TableCell EpisodeCellLeft = new TableCell();
                    TableCell EpisodeCellRight = new TableCell();
                    Table InfoTable = new Table();
                    TableRow Info1Row = new TableRow();
                    TableCell Info1Cell = new TableCell();
                    TableRow Info2Row = new TableRow();
                    TableCell Info2Cell = new TableCell();
                    TableRow Info3Row = new TableRow();
                    TableCell Info3Cell = new TableCell();
                    TableRow Info3xRow = new TableRow();
                    TableCell Info3xCell = new TableCell();
                    TableRow Info4Row = new TableRow();
                    TableCell Info4Cell = new TableCell();
                    Image ThumbImage = new Image();
                    HyperLink TitleHun = new HyperLink();
                    Label Status = new Label();
                    Label TitleOrig = new Label();
                    Label ReleaseDate = new Label();
                    Label Description = new Label();
                    HtmlControl DivControl = new HtmlGenericControl("div");
                    HtmlControl youtubeControl = new HtmlGenericControl("img");

                    EpisodePanel.ID = "EpisodePanel" + item.id.ToString();
                    EpisodeTable.ID = "EpisodeTable" + item.id.ToString();
                    EpisodeRow.ID = "EpisodeRow" + item.id.ToString();
                    EpisodeCellLeft.ID = "EpisodeCellLeft" + item.id.ToString();
                    EpisodeCellRight.ID = "EpisodeCellRight" + item.id.ToString();
                    ThumbImage.ID = "ThumbImage" + item.id.ToString();
                    TitleHun.ID = "TitleHun" + item.id.ToString();
                    Status.ID = "Status" + item.id.ToString();
                    TitleOrig.ID = "TitleOrig" + item.id.ToString();
                    ReleaseDate.ID = "ReleaseDate" + item.id.ToString();
                    Description.ID = "Description" + item.id.ToString();
                    DivControl.ID = "Facebook" + item.id.ToString();

                    EpisodePanel.CssClass = "previewPanel";
                    TitleHun.CssClass = "previewTitleHun";
                    Status.CssClass = "previewStatus";
                    TitleOrig.CssClass = "previewTitleOrig";
                    ReleaseDate.CssClass = "previewReleaseDate";
                    Description.CssClass = "previewDescription";

                    if (item.imgUrl != "")
                        ThumbImage.ImageUrl = "~/Pic/" + item.imgUrl;
                    else
                        ThumbImage.ImageUrl = "~/images/nopic.png";
                    ThumbImage.Width = 120;
                    ThumbImage.Height = 120;
                    TitleHun.Text = item.titleHun;
                    TitleHun.NavigateUrl = "ViewEpisode.aspx?epizod=" + item.id.ToString();
                    DivControl.Attributes.Add("class", "fb-like");
                    DivControl.Attributes.Add("href", "www.sorozatportal.hu/ViewEpisode.aspx?epizod=" + item.id.ToString());
                    DivControl.Attributes.Add("send", "true");
                    DivControl.Attributes.Add("width", "450");
                    DivControl.Attributes.Add("show-faces", "true");
                    youtubeControl.Attributes.Add("class", "youtube");
                    youtubeControl.Attributes.Add("id", item.videoUrl);
                    youtubeControl.Attributes.Add("src", "youtube.png");
                    youtubeControl.Attributes.Add("title", "Kattints az előzetesért!");
                    youtubeControl.Attributes.Add("style", "cursor: pointer;");
                    TitleOrig.Text = item.titleOrig;
                    ReleaseDate.Text = String.Format("{0:yyyy.MM.dd}", item.releaseDate);
                    if (item.description.Length > 500)
                        Description.Text = item.description.Substring(0, 500) + "...";
                    else
                        Description.Text = item.description;

                    Info1Cell.Controls.Add(TitleHun);
                    Info2Cell.Controls.Add(TitleOrig);
                    if (item.status != 1)
                    {
                        Status.Text = "   (Nem engedélyezett)";
                        Info2Cell.Controls.Add(Status);
                    }
                    Info3Cell.Controls.Add(ReleaseDate);
                    if (!String.IsNullOrEmpty(item.videoUrl)) Info3xCell.Controls.Add(youtubeControl);
                    Info4Cell.Controls.Add(Description);

                    Info1Row.Controls.Add(Info1Cell);
                    Info2Row.Controls.Add(Info2Cell);
                    Info3Row.Controls.Add(Info3Cell);
                    if (!String.IsNullOrEmpty(item.videoUrl)) Info3xRow.Controls.Add(Info3xCell);
                    Info4Row.Controls.Add(Info4Cell);

                    InfoTable.Controls.Add(Info1Row);
                    InfoTable.Controls.Add(Info2Row);
                    InfoTable.Controls.Add(Info3Row);
                    if (!String.IsNullOrEmpty(item.videoUrl)) InfoTable.Controls.Add(Info3xRow);
                    InfoTable.Controls.Add(Info4Row);

                    EpisodeCellLeft.Controls.Add(ThumbImage);
                    EpisodeCellRight.Controls.Add(InfoTable);

                    EpisodeRow.Controls.Add(EpisodeCellLeft);
                    EpisodeRow.Controls.Add(EpisodeCellRight);
                    EpisodeTable.Controls.Add(EpisodeRow);
                    FieldSet.Controls.Add(EpisodeTable);
                    FieldSet.Controls.Add(DivControl);

                    EpisodesPanel.Controls.Add(FieldSet);
                }
            }

            //CommentPanelForm.CssClass = "panel";
            CreateListComments();
        }
        catch (Exception) { 
        
        }
    }

    protected void CommentSubmit_Click(object sender, EventArgs e)
    {
        try{
            newComment = new Comment();
            if (CommentContent.Text == "")
            {
                Alert.Show("A hozzászólás szövege nem lehet üres!");
                return;
            }
            else
            {
                String s = Request.QueryString["evad"].ToString();
                season = data.GetWholeSeason(Convert.ToInt32(s), true);

                newComment.seriesId = season.seriesId;
                newComment.seasonId = season.id;
                newComment.episodeId = 0;
                newComment.title = CommentTitle.Text;
                newComment.content = CommentContent.Text;
                newComment.userId = Functions.GetUserId(); 

                Boolean success = data.InsertComment(newComment);

                if (!success)
                {
                    Alert.Show("Hiba történt a hozzászólás létrehozása során!");
                }
                else
                {
                    CommentTitle.Text = "";
                    CommentContent.Text = "";
                    CommentPanelList.Controls.Clear();
                    CreateListComments();
                }
            }
        }
        catch (Exception)
        {
            Alert.Show("Hiba történt a hozzászólás létrehozása során!");
        }
    }

    private void CreateListComments()
    {
        try
        {
            comments = data.GetComments(season.seriesId, season.id, 0);


            foreach (Comment item in comments)
            {
                Panel CommentPanel = new Panel();
                HtmlGenericControl FieldSet = new HtmlGenericControl("fieldset");
                Table CommentTable = new Table();
                TableRow CommentRow = new TableRow();
                TableCell CommentCellLeft = new TableCell();
                TableCell CommentCellRight = new TableCell();
                Table CommentPicTable = new Table();
                TableRow CommentPic1Row = new TableRow();
                TableCell CommentPic1Cell = new TableCell();
                TableRow CommentPic2Row = new TableRow();
                TableCell CommentPic2Cell = new TableCell();
                Table CommentInfoTable = new Table();
                TableRow CommentInfo1Row = new TableRow();
                TableCell CommentInfo1Cell = new TableCell();
                TableRow CommentInfo2Row = new TableRow();
                TableCell CommentInfo2Cell = new TableCell();
                TableRow CommentInfo3Row = new TableRow();
                TableCell CommentInfo3Cell = new TableCell();

                Image ThumbImage = new Image();
                Label CreatedDate = new Label();
                Label UserName = new Label();
                Label Title = new Label();
                Label Content = new Label();

                CommentPanel.ID = "CommentPanel" + item.id.ToString();
                CommentTable.ID = "CommentTable" + item.id.ToString();
                CommentRow.ID = "CommentRow" + item.id.ToString();
                CommentCellLeft.ID = "CommentCellLeft" + item.id.ToString();
                CommentCellRight.ID = "CommentCellRight" + item.id.ToString();
                ThumbImage.ID = "ThumbImage" + item.id.ToString();
                CreatedDate.ID = "CreatedDate" + item.id.ToString();
                UserName.ID = "UserName" + item.id.ToString();
                Title.ID = "Title" + item.id.ToString();
                Content.ID = "Content" + item.id.ToString();

                CommentPanel.CssClass = "commentPanel";
                CommentTable.CssClass = "commentTable";
                CommentCellLeft.CssClass = "commentTableLeft";
                CommentCellRight.CssClass = "commentTableRight";
                CommentInfoTable.CssClass = "commentInfoTable";
                CreatedDate.CssClass = "commentCreatedDate";
                UserName.CssClass = "commentUserName";
                Title.CssClass = "commentTitle";
                Content.CssClass = "commentContent";

                ThumbImage.ImageUrl = "~/images/nopic.gif";
                ThumbImage.Width = 150;
                ThumbImage.Height = 150;
                UserName.Text = data.GetUserById(item.userId);
                CreatedDate.Text = String.Format("{0:yyyy.MM.dd HH:mm:ss}", item.createdDate);
                Title.Text = item.title;
                Content.Text = item.content;

                CommentPic1Cell.HorizontalAlign = HorizontalAlign.Center;
                CommentPic2Cell.HorizontalAlign = HorizontalAlign.Center;
                CommentInfo1Cell.HorizontalAlign = HorizontalAlign.Right;

                CommentCellLeft.VerticalAlign = VerticalAlign.Top;
                CommentCellRight.VerticalAlign = VerticalAlign.Top;

                CommentPic1Cell.Controls.Add(ThumbImage);
                CommentPic2Cell.Controls.Add(UserName);
                CommentInfo1Cell.Controls.Add(CreatedDate);
                CommentInfo2Cell.Controls.Add(Title);
                CommentInfo3Cell.Controls.Add(Content);

                CommentPic1Row.Controls.Add(CommentPic1Cell);
                CommentPic2Row.Controls.Add(CommentPic2Cell);
                CommentInfo1Row.Controls.Add(CommentInfo1Cell);
                CommentInfo2Row.Controls.Add(CommentInfo2Cell);
                CommentInfo3Row.Controls.Add(CommentInfo3Cell);

                CommentPicTable.Controls.Add(CommentPic1Row);
                CommentPicTable.Controls.Add(CommentPic2Row);
                CommentInfoTable.Controls.Add(CommentInfo1Row);
                CommentInfoTable.Controls.Add(CommentInfo2Row);
                CommentInfoTable.Controls.Add(CommentInfo3Row);

                CommentCellLeft.Controls.Add(CommentPicTable);
                CommentCellRight.Controls.Add(CommentInfoTable);

                CommentRow.Controls.Add(CommentCellLeft);
                CommentRow.Controls.Add(CommentCellRight);
                CommentTable.Controls.Add(CommentRow);
                FieldSet.Controls.Add(CommentTable);

                CommentPanelList.Controls.Add(FieldSet);
            }
        }
        catch (Exception)
        {

        }
    }

    protected void StatusMinusButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["evad"].ToString();
        if (data.UpdateSeasonStatus(Convert.ToInt32(s), -1))
        {
            Initialize(Convert.ToInt32(s));
        }
        else
        {
            Alert.Show("Az évadot nem sikerült letiltani!");
        }
    }

    protected void StatusPlusButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["evad"].ToString();
        if (data.UpdateSeasonStatus(Convert.ToInt32(s), 1))
        {
            Initialize(Convert.ToInt32(s));
        }
        else
        {
            Alert.Show("A sorozatot nem sikerült engedélyezni!");
        }
    }

    protected void EditButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["evad"].ToString();
        Response.Redirect("~/ModifySeason.aspx?evad=" + s);
    }

    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        String s = Request.QueryString["evad"].ToString();
        if (data.DeleteSeason(Convert.ToInt32(s)))
        {
            Response.Redirect("~/Series.aspx");
        }
        else
        {
            Alert.Show("A törlés során hiba lépett fel!");
        }
    }
    protected void Rating_Changed(object sender, EventArgs e)
    {

    }
}